import Taro, {useDidShow} from "@tarojs/taro";
import dayjs from 'dayjs'
import {Image, ScrollView, Swiper, SwiperItem, Text, View} from "@tarojs/components";
import {useEffect, useState} from "react";
import {getRealPx} from "../../utils/helper";
import './index.scss'
import CustomHeader from "../../components/customHeader";
import {getGlobalData} from "../../utils/globalData";

export default () => {

  const [cinema,setCinema]=useState({})

  const {router} = Taro.getCurrentInstance()

  const bgHeight=getGlobalData('statusBarHeight')+getGlobalData('headerHeight')+30

  const [theme,setTheme]=useState(1)
  const [curDate,setcurDate]=useState(0)

  const [data, setData] = useState({
    movieIndex: -1,
    cinemaId:0,
    dateIndex: 0,
    movieList: [],
    planList: []
  })
  const [swiperMargin, setSwiperMargin] = useState({
    movie: 0,
    date: 0
  })
  const movieSwiperChange = evt => {
    setcurDate(0)
    setData({...data, movieIndex: evt.detail.current})
  }
  const getShowDate = (date) => {
    const weekList = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    const d = dayjs(date)
    if (dayjs().format('YYYY-MM-DD') == date) {
      return `今天 ${d.format('MM-DD')}`
    } else if (dayjs().add(1, 'day').format('YYYY-MM-DD') == date) {
      return `明天 ${d.format('MM-DD')}`
    } else if (dayjs().add(2, 'day').format('YYYY-MM-DD') == date) {
      return `后天 ${d.format('MM-DD')}`
    } else {
      return `${weekList[d.day()]} ${d.format('MM-DD')}`
    }
  }

  const buyTicket = (item) => {
    Taro.navigateTo({
      url: `/mainPages/cinemaSeat/index?id=${item.id}&filmName=${encodeURIComponent(data.movieList[data.movieIndex].filmNickName)}`
    })
  }

  const tellPhone=()=>{
    Taro.makePhoneCall({
      phoneNumber:cinema.contactPhone
    })
  }

  const toMap=()=>{
    Taro.openLocation({
      latitude: parseFloat(cinema.latitude),
      longitude: parseFloat(cinema.longitude),
      scale: 18,
      name: cinema.cinemaNickName,
      address: cinema.address,
    })
    // Taro.navigateTo({
    //   url: `/mainPages/map/index?lat=${cinema.latitude}&lng=${cinema.longitude}&name=${encodeURIComponent(cinema.cinemaNickName)}`
    // })
  }


  useDidShow(()=>{
    setCinema(Taro.getStorageSync('selectMerchant')||{})
  })
  useEffect(() => {
    setSwiperMargin({
      movie: getRealPx(275),
      date: getRealPx(540),
    })
    if(cinema.id){
      Taro.$get('/cinema-app/api/v1/film/hotFilm', {
        cinemaId: cinema.id,
        cityId: cinema.cityId
      }).then(res => {
        if (res.code == '1') {
          const _movieList=res.content.map(item => {
            return item
          })
          const index=_movieList.findIndex(item=>item.id==router.params.id)
          const movieIndex=index<0?0:index
          setData({
            ...data,
            movieList: _movieList,
            movieIndex,
            cinemaId:cinema.id
          })
        }
      })
    }
  }, [cinema.id]);

  const handleScroll=(evt)=>{
    if(evt.detail.scrollTop>30){
      setTheme(0)
    }else{
      setTheme(1)
    }
  }

  const fetchPlan=()=>{
    if (data.movieList.length > 0) {
      Taro.$get('/cinema-app/api/v1/plan/byCinemaAndFilm', {
        cinemaId: cinema.id,
        filmId: data.movieList[data.movieIndex].id
      }).then(res => {
        if (res.code == '1') {
          setData({
            ...data,
            dateIndex: 0,
            planList: res.content.sort((a, b) => {
              return a.planDate > b.planDate ? 1 : -1
            }).map(item => {
              item.showDate = getShowDate(item.planDate)
              item.planList = item.planList.map(r => {
                r.showTimeStart = dayjs(r.showTimeStart).format('HH:mm')
                r.showTimeEnd = dayjs(r.showTimeEnd).format('HH:mm')
                r.listingPrice = parseFloat(r.listingPrice)
                r.standardPrice = parseFloat(r.standardPrice)
                return r
              })
              return item
            })
          })
        }
      })
    }
  }

  useEffect(() => {
    fetchPlan()
  }, [data.movieIndex,data.cinemaId]);

  return (
    <ScrollView onScroll={handleScroll} scrollY style={{height:'100vh'}}>
      <CustomHeader theme={theme} pad={false}>
        <View className='header-text'>选择排期</View>
      </CustomHeader>
      {
        !data.movieList.length ? '' :
          <View className='page'>
            <View className='bg' style={{height:`${bgHeight}px`,backgroundImage: `url(${data.movieList[data.movieIndex].filmPosterUrl})`}}></View>
            <View className='page-content'>
              <View className='white-bg'>
                <View className='part-1 flex-cc'>
                  <View className='col-1 flex-cs'>
                    <View className='r-1' onClick={()=>{
                      Taro.navigateTo({
                        url:'/mainPages/cinema-detail/index'
                      })
                    }}
                    >
                      <View className='flex-cs'>
                        <View className='i-1 ellipsis'>{cinema.cinemaNickName}</View>
                        <View className="at-icon at-icon-chevron-right"></View>
                      </View>
                    </View>
                    <View className='r-2'>
                      <View className='flex-cs'>
                        <View className='ellipsis'>{cinema.address}</View> <View>· {cinema.distance}</View>
                      </View>
                    </View>
                  </View>
                  <View className='col-2 flex-cc'>
                    <View className='c-1 flex-cc' onClick={toMap}>
                      <Image className='img' mode='widthFix' src={require('@/images/ticket/wz.png')}></Image>
                      <Text>地图</Text>
                    </View>
                    <View className='c-2 flex-cc' onClick={tellPhone}>
                      <Image className='img' mode='widthFix' src={require('@/images/ticket/dh.png')}></Image>
                      <Text>电话</Text>
                    </View>
                  </View>
                </View>
                <View className='part-2'>
                  <Swiper onChange={movieSwiperChange} current={data.movieIndex} displayMultipleItems={1}
                    previousMargin={swiperMargin.movie} nextMargin={swiperMargin.movie} className='row-1'
                  >
                    {data.movieList.map((item, index) => {
                      return (
                        <SwiperItem onClick={() => {
                          setData({...data, movieIndex: index})
                        }}
                        >
                          <View className={`swiper-box ${index === data.movieIndex ? 'active' : ''}`}>
                            <Image className='swiper-img'
                              src={!item.filmPosterUrl?.includes('alicdn')?item.filmPosterUrl:item.filmPosterUrl+'_400x400'}
                              mode='aspectFill'
                            />
                          </View>
                        </SwiperItem>
                      )
                    })}
                  </Swiper>
                  <View className='row-2 flex-cc'>
                    <View className='r-1'>{data.movieList[data.movieIndex].filmNickName}</View>
                    <View className='r-2'>{data.movieList[data.movieIndex].filmType} | {data.movieList[data.movieIndex].duration}分钟</View>
                  </View>
                </View>
              </View>
              <View className='part-3'>
                <Swiper className='row-1' displayMultipleItems={1} current={curDate} onChange={e=>{
                  setcurDate(e.detail.current)
                }} nextMargin={swiperMargin.date}>
                  {
                    data.planList.map((item, index) => {
                      return (
                        <SwiperItem onClick={() => {
                          setData({...data, dateIndex: index})
                        }}
                        >
                          <View className={`flex-cc ${index == data.dateIndex ? 'active' : ''}`}>
                            {item.showDate}
                          </View>
                        </SwiperItem>
                      )
                    })
                  }
                </Swiper>
                <View className='row-2'>
                  {/*<View className='vip flex-cc'>*/}
                  {/*  <View className='flex-cs'>*/}
                  {/*    <Image className='i-1' src={require('@/images/ticket/vip.png')}></Image>*/}
                  {/*    <Text className='i-2'>开通即享超值会员价</Text>*/}
                  {/*  </View>*/}
                  {/*  <View className='i-3'>¥18.8元开通</View>*/}
                  {/*</View>*/}
                  <View>
                    {
                      !data.planList.length ? '' :
                        data.planList[data.dateIndex].planList.map(item => {
                          return (
                            <View className='item'>
                              <View className='c-1'>
                                <View className='i-1'>{item.showTimeStart}</View>
                                <View className='i-2'>{item.showTimeEnd}散场</View>
                              </View>
                              <View className='c-2'>
                                <View className='i-1'>{item.filmLanguage} {item.filmVersion}</View>
                                <View className='i-2 ellipsis'>{item.hallNickName}</View>
                              </View>
                              <View className='c-3'>
                                <View className='i-1'>
                                  <Text>¥</Text>
                                  <Text className='num'>{item.salePrice}</Text>
                                  <Text>起</Text>
                                </View>
                                {item.memberPrice?
                                <View className='i-2'>
                                  <Text className='label'>会员卡</Text>
                                  <View>
                                    <Text>¥</Text>
                                    <Text className='num'>{item.memberPrice}</Text>
                                    <Text>起</Text>
                                  </View>
                                </View>:null}
                              </View>
                              <View className='c-4'>
                                <View className='flex-cc' onClick={() => {
                                  buyTicket(item)
                                }}
                                >购票</View>
                              </View>
                            </View>
                          )
                        })
                    }
                  </View>
                </View>
              </View>
            </View>
          </View>
      }
    </ScrollView>
  )
}
